$(document).ready(function(){
	$('.bl-ft-accord dl, .un-ls-col dl').accordWithIcon();
	$('[placeholder]').placeholderInput();
	$('.bl-ls').actionTable();
	$('.bl-ls-form .el-help').aTooltip();
	$('.gl-tabs').searchChange();
	$('.bl-ds').actionDetails();
	$('.bl-st').actionSettings();
	$('.un-ds-note .el-help a').aTooltip({tipClass:'bl-side-tip', xOffset:270});
	$('.bl-ls-place .el-btn-blue').aModal({modalCustom:'#modal_allow_complete'});
});
if(jQuery)(function($){
	//
	$.fn.aTooltip = function(params){
		 var conf=$.extend({
			tipClass:'bl-tip',
			ifClick:true,
			xOffset:90,
			yOffset:10,
			tipPosition:'bottom',
			tipCustom:null,
			ifLoad:false
		}, params);
		return this.each(function(){
			var $o=$(this), f=this, c=conf, tipContent;
			if(c.tipCustom){
				tipContent=$(c.tipCustom).html();
			}else if(f.hash!=undefined && $(f.hash).length){
				tipContent=$(f.hash).html();
				$(f.hash).remove();
			}else if($o.prop('title').length){
				tipContent=$o.prop('title');
				$o.prop('title','');
			}else{return true}
			var $tip_arrow=$('<span class="el-tip-'+c.tipPosition+'"></span>'), $tip_close=$('<a class="el-tip-close" href="#" title="Sluiten">Sluiten</a>');
			$.extend(f,{
				_get_box:function(){return $('.'+c.tipClass)},
				_build:function(){
					$('body').append($('<div class="'+c.tipClass+'">'+tipContent+'</div>'));
					f._get_box().append($tip_arrow);
					if(c.ifClick){f._get_box().append($tip_close)}
				},
				_position:function(){
					var o_position=$o.offset();
					if(c.tipPosition=='top'){
						f._get_box().css({
							top:(o_position.top-f._get_box().innerHeight()-c.yOffset),
							left:(o_position.left+($o.innerWidth()/2)-c.xOffset)
						});
					}else if(c.tipPosition=='bottom'){
						f._get_box().css({
							top:(o_position.top+$o.outerHeight()+c.yOffset),
							left:(o_position.left+($o.innerWidth()/2)-c.xOffset)
						});
					}else if(c.tipPosition=='right'){
						f._get_box().css({
							top:(o_position.top-c.yOffset),
							left:(o_position.left+($o.outerWidth())+c.xOffset)
						});
					}
				},
				_remove:function(){
				  f._get_box().remove();
				}
			});
			if(c.ifLoad){
				f._build();
				f._position();
				f._get_box().find('.el-tip-close').click(function(){
					$(window).unbind('tooltip_move');
					f._remove();
					return false;
				});
			}else{
				if(!c.ifClick){	
					$o.hover(function(){
						f._get_box().remove();
						f._build();
						f._position();
					}, function(){ 
						f._remove();
					});
				}else{
					$o.click(function(el){
						f._get_box().remove();
						f._build();
						f._position();
						$(window).bind('tooltip_move', function(){f._position()})
						f._get_box().find('.el-tip-close').click(function(){
							$(window).unbind('tooltip_move');
							f._remove();
							return false;
						});
						return false;			
					});
					$(window).bind('resize', function(){$(this).trigger('tooltip_move')})
				}
			}
		});
  };
	//
	$.fn.aModal = function(params){
		 var conf=$.extend({
			modalCustom:null,
			ifClick:true
		}, params);
		return this.each(function(){
			var $o=$(this), f=this, c=conf, $modalContent;
			if(c.modalCustom){
				$modalContent=$(c.modalCustom);
			}else if(f.hash!=undefined && $(f.hash).length){
				$modalContent=$(f.hash);
			}else{return true}
			var $modal_overlay=$('<div class="gl-modal-overlay"></div>'), $modal_close=$('<a class="el-modal-close" href="#" title="Sluiten">Sluiten</a>'), modal_w, modal_h;
			$.extend(f,{
				_build:function(){
					$modalContent.append($modal_close);
				},
				_show:function(){
					$('body').append($modal_overlay);
					if(c.ifClick){
						$modal_overlay.on('click', function(){f._hide()});
					}
					$modalContent.css({display:'block', position:'fixed', zIndex:11000, top:'-999em', left:'-999em'});
					modal_w=$modalContent.innerWidth(), modal_h=$modalContent.innerHeight();
					$modal_overlay.fadeTo(200, 1);
					$modalContent.css({opacity:0, left:'50%', marginLeft:-(modal_w/2), top:($(window).height()/2)-modal_h}).fadeTo(200, 1);
				},
				_hide:function(){
				  $modal_overlay.fadeTo(200, 0, function(){$modal_overlay.remove()});
					$modalContent.fadeTo(200, 0, function(){$modalContent.hide()});
				}
			});
			f._build()
			$modal_close.on('click', function(){
				f._hide();
				return false;
			})
			$o.on('click', function(){
				f._show();
				return false;
			});
		});
  };
	//
	$.fn.accordWithIcon = function(params){
		var conf = $.extend({
			headElement:'dt',
			bodyElement:'dd'
		}, params);
		return this.each(function(){
			var c=conf, o=$(this);
			o.children().each(function(){
				if($(this).is(c.headElement)){
					if($(this).next().is(c.bodyElement)){
						var heading=$(this), hull=$(this).next();
						hull.hide();
						if(hull.html()!=''){
							var head_icon=$('<span class="el-icon">+</span>'),
									head_anchor=$('<a href="#"></a>').html(heading.html());
							heading.empty().append(head_icon).append(head_anchor).addClass('el-close');
							head_anchor.on('click', function(e){
								head_icon.trigger('click');
								e.preventDefault();
							});
							head_icon.on('click', function(){
								if(heading.hasClass('el-close')){
									hull.stop().slideDown();
									heading.removeClass('el-close');
									head_icon.html('-');
								}else{
									hull.stop().slideUp();
									heading.addClass('el-close');
									head_icon.html('+');
								}
							});
						}
						if($(this).hasClass('el-open')){
							hull.show();
							heading.removeClass('el-close').removeClass('el-open');
							head_icon.html('-');
						}
					}
				}
			})
		})
	};
	//
	$.fn.actionDetails = function(params){
		var conf=$.extend({
			toolTip:'.el-help',
			addressShow:'el-form-address',
			addressBlock:'.un-ds-address',
			criteriaShow:'el-form-criteria',
			criteriaBlock:'.un-ds-criteria',
			accordBlock:'dl.un-ds-reg',
			sideToPrint:'.un-ds-note'
		}, params);
		return this.each(function(){
			var	c=conf, $o=$(this), $tip=$(c.toolTip, $o), $inp=$('input[type="checkbox"], input[type="radio"]', $o), $adr_input=$('.'+c.addressShow, $o), $adr_block=$(c.addressBlock, $o), $crt_input=$('.'+c.criteriaShow, $o), $crt_block=$(c.criteriaBlock, $o), $acrd=$(c.accordBlock, $o), $acrd_close=$('<a class="el-close" href="#" title="Sluiten">Sluiten</a>');
			$o.find('.un-ds-ttl').after($(c.sideToPrint).clone())
			$tip.aTooltip({tipPosition:'right', xOffset:10, yOffset:30, tipClass:'bl-ds-tip'});
			$inp.emulationInput();
			$acrd.accordWithIcon();
			$acrd.children('dd').append('<span class="el-arrow"></span>', $acrd_close)
			$acrd_close.on('click', function(){
				$acrd.find('dt .el-icon').trigger('click');
				return false;
			})
			if($adr_input.length==1 && $adr_block.length==1){
				$adr_input.on('change', function(){
					if($(this).is(':checked')){
						$adr_block.show();
					}else{
						$adr_block.hide();
					}
					$(window).resize();
				})
				if($adr_input.is(':checked')){$adr_block.show()}else{$adr_block.hide()}
			};
			
			if($crt_input.length==1 && $crt_block.length==1){
				$o.find($('input[type="radio"]').prop('name',$crt_input.prop('name'))).each(function(){
					$(this).on('click', function(){
						if($crt_input.is(':checked')){
							$crt_block.show();
						}else{
							$crt_block.hide();
						}
						$(window).resize();
					})
				});
				if($crt_input.is(':checked')){$crt_block.show()}else{$crt_block.hide()}
			}
			
		})
	};
	//
	$.fn.actionSettings = function(params){
		var conf=$.extend({
			passwordBlock:'.un-st-pass',
			criteriaBlock:'.un-st-crit',
			criteriaUrl:'include/criteria.php'
		}, params);
		return this.each(function(){
			var	c=conf, $o=$(this), f=this, $psw_block=$(c.passwordBlock, $o), $crt_block=$(c.criteriaBlock, $o), $crt_data;
			$.extend(f,{
				_psw_check:function(){
					var $btn=$('button', $psw_block), $new_psw=$('input#new_passw', $psw_block), $new_psw_rpt=$('input#new_passw_rep', $psw_block);
					if($btn.length==1 && $new_psw.length==1 && $new_psw_rpt.length==1){
						$btn.prop('disabled', true);
						f._psw_inp($new_psw, $new_psw_rpt, $btn);
						f._psw_inp($new_psw_rpt, $new_psw, $btn)
					}
				},
				_psw_inp:function(c_inp, h_inp, btn){
					c_inp.on('change keyup', function(){
						if(c_inp.val().length && c_inp.val()==h_inp.val()){
							btn.prop('disabled', false);
						}else{
							btn.prop('disabled', true);
						}
					});
				},
				_crt_init:function(){
					var $form=$('.un-generic-form', $crt_block), $inp, $btn;
					$form.append(
						'<div class="un-row cf">'
							+'<label for="new_crit">Voer een criterium in</label>'
							+'<input id="new_crit" type="text" name="new_crit" value="">'
							+'<button type="submit" disabled="disabled" class="el-btn-blue"><span>Toevoegen</span></button>'
						+'</div>')
					$inp=$form.find('input[type="text"]'), $btn=$form.find('button'), $crt_data=$('.un-generic', $crt_block);
					$inp.on('change keyup', function(e){
						if($inp.val().length){
							$btn.prop('disabled', false);
						}else{
							$btn.prop('disabled', true);
						}
						if($inp.val().length && e.keyCode==13){$btn.click()}
					});
					$btn.on('click', function(){
						f._crt_update($inp);
						return false;
					});
					f._crt_load();
				},
				_crt_load:function(){
					$.ajax({
						url:c.criteriaUrl,
						dataType:'json',
						cache:false,
						beforeSend:function(){
							$('.un-row', $crt_data).hide();
							$crt_data.append('<p>Loading...</p>');
						},
						error:function(xhr, status, error){
							$crt_data.empty().append('<div class="un-error">'+error+'</div>');
						},
						success:function(data){
							f._parse_json(data);
						}
					});
				},
				_crt_edit:function($in_data){
					var $v_data=$in_data.find('.el-name');
					$in_data.find('.el-name, .el-edit, .el-up, .el-down, .el-del').hide();
					$in_data.append(
						'<li class="el-form-edit">'
							+'<input id="edit_crit" type="text" name="edit_crit" value="'+$v_data.text()+'">'
							+'<button type="submit" class="el-btn-blue"><span>Bewaren</span></button>'
						+'</li>');
					var $i_data=$in_data.find('input[type="text"]'),$b_data=$in_data.find('button');
					$i_data.focus();
					$i_data.on('change keyup', function(e){
						if($i_data.val().length){
							$b_data.prop('disabled', false);
						}else{
							$b_data.prop('disabled', true);
						}
						if($i_data.val().length && e.keyCode==13){$b_data.click()}
						if(e.keyCode==27){$in_data.find('.el-name, .el-edit, .el-up, .el-down, .el-del').show(); $in_data.find('.el-form-edit').remove()}
					});
					$b_data.on('click', function(){
						$v_data.prop('title', $i_data.val()).text($i_data.val())
						f._crt_update();
						return false;
					});
				},
				_crt_update:function(in_inp){
					var jqdata=[];
					$('.un-row', $crt_data).each(function(){
						var jqitem={};
						if($(this).find('.el-date').text().length){
							jqitem.date=$(this).find('.el-date').text();
						}
						jqitem.name=$(this).find('.el-name').text();
						jqdata.push(jqitem)
					});
					if(in_inp!=undefined){jqdata.push({"name":in_inp.val()})}
					$.ajax({
						url:c.criteriaUrl,
						dataType:'json',
						cache:false,
						type:'post',
						data:{"criteria_save":JSON.stringify(jqdata)},
						beforeSend:function(){
							$crt_data.css({minHeight:$crt_data.height()})
							$('.un-row', $crt_data).hide();
							$crt_data.append('<p>Loading...</p>');
						},
						error:function(xhr, status, error){
							$crt_data.empty().append('<div class="un-error">'+error+'</div>');
						},
						success:function(data){
							f._parse_json(data);
							$crt_data.css({minHeight:0});
						}
					});
				},
				_parse_json:function(d){
					$crt_data.empty();
					$.each(d, function(i){
						$crt_data.append('<ul class="un-row cf">'
							+'<li class="el-date">'+(this.date?this.date:'')+'</li>'
							+'<li class="el-name"><span title="'+this.name+'">'+this.name+'</span></li>'
							+'<li class="el-edit"><a href="#" title="Wijzigen">Wijzigen</a></li>'
							+'<li class="el-del"><a href="#" title="Verwijderen">Verwijderen</a></li>'
							+'<li class="el-up">'+(i?'<a href="#" title="Omhoog">Omhoog</a>':'<span></span>')+'</li>'
							+'<li class="el-down">'+(i==d.length-1?'<span></span>':'<a href="#" title="Omlaag">Omlaag</a>')+'</li>'
						+'</ul>');
					})
					$('.un-row', $crt_data).each(function(i){
						var rw=$(this);
						$(this).find('.el-del a').on('click', function(){
							rw.remove();
							f._crt_update();
							return false;
						});
						$(this).find('.el-up a').on('click', function(){
							$('.un-row', $crt_data).eq(i-1).before(rw);
							f._crt_update();
							return false;
						});
						$(this).find('.el-down a').on('click', function(){
							$('.un-row', $crt_data).eq(i+1).after(rw);
							f._crt_update();
							return false;
						});
						$(this).find('.el-edit a').on('click', function(){
							f._crt_edit($('.un-row', $crt_data).eq(i));
							return false;
						});
					})
				}
			});
			$o.find('.un-st-accord').accordWithIcon({headElement:'h3', bodyElement:'.un-st-data'});
			f._psw_check();
			f._crt_init();
		})
	};
	//
	$.fn.eqElements = function(params){
		var conf=$.extend({
			elementGet:'.bl-dm-form, .bl-dm-list'
		}, params);
		return this.each(function(){
			var	c=conf, el=$(c.elementGet, $(this)), height=0;
			el.each(function(){
				height=Math.max(height, $(this).height());
			});
			el.each(function(){
				$(this).css('height', height);
			});
		})
	};
	//
	$.fn.placeholderInput = function(params){
		var conf=$.extend({
			classDef:'el-def'
		}, params);
		return this.each(function(){
			var f=this;
			if(f.placeholder && 'placeholder' in document.createElement(f.tagName)) return;
			var $o=$(this), c=conf, placeholder = f.getAttribute('placeholder');
			if(f.value === '' || f.value == placeholder){
				$o.addClass(c.classDef);
				f.value=placeholder;
			}
			$o.on('focus', function(){
				if($o.hasClass(c.classDef)){
					this.value='';
					$o.removeClass(c.classDef)
				}
			}).on('blur', function(){
				if(this.value === ''){
					$o.addClass(c.classDef);
					this.value=placeholder;
				}else{
					$o.removeClass(c.classDef);
				}
			});
			f.form && $(f.form).submit(function(){
				if($o.hasClass(c.classDef)){
					that.value='';
				}
			});
		})
	};
	//
	$.fn.searchChange = function(params){
		var conf=$.extend({
			elementForm:'div[data-radio-id]',
			elementChange:'.un-form-type input[type="radio"]'
		}, params);
		return this.each(function(){
			var	c=conf, f=this, $o=$(this), $r_element=$(c.elementChange, $o), $f_element=$o.find(c.elementForm), $tbs=$('.bl-ls-tabs a', $o), $m_inp=$('#code_brief', $o);
			$.extend(f,{
				_eq_tabs:function(){
					$tbs.css({'height':'auto'});
					$tbs.css({'height':$o.innerHeight()-50});
				},
				_change_form:function(rd, fs){
					$f_element.hide(); $('.bl-form-tip').hide();
					$f_element.each(function(){
						if($(this).data('radio-id')==rd.prop('id')){
							$(this).show();
							var $inp=$(this).find('input[type="text"]:first');
							if($inp.data('hint') && fs){
								$inp.focus();
								$inp.aTooltip({ifLoad:true, tipClass:'bl-form-tip', tipCustom:'#'+$inp.data('hint'), xOffset:95, yOffset:12});
								$('.bl-form-tip').find('tr').hover(function(){$(this).addClass('el-hover')}, function(){$(this).removeClass('el-hover')});
							}
						}
						
					});
					f._eq_tabs();
				}
			});
			var m_inp_v=$m_inp.val();
			$m_inp.mask('a-9999-9999').val(m_inp_v);
			if(!$r_element.filter(':checked').length){
				$r_element.eq(0).click();
			}
			$r_element.each(function(){
				var $rd=$(this);
				if($rd.is(':checked')){
					f._change_form($rd, true);
				}
				$rd.on('change', function(){
					f._change_form($rd);
				})
			})
			$r_element.emulationInput();
		})
	};
	//
	$.fn.emulationInput = function(params){
		var conf = $.extend({
			checkboxClass:'el-btn-chk',
			radioClass:'el-btn-rdo'
		}, params);
		return this.each(function(){
			var $o=$(this), c=conf, $w=$o.prop('type')=='checkbox'?'<span class="' + c.checkboxClass + '" />':'<span class="' + c.radioClass + '" />';
			if($o.attr('type')=='checkbox'){
				$o.css({opacity:0}).wrap($w);
				$o.parent().append('<em>&#10004;</em>')
				$o.on('change', function(){
					if($o.is(':checked')) $o.parent().addClass(c.checkboxClass+'-on');
					else $o.parent().removeClass(c.checkboxClass+'-on');
				});
				if($o.is(':checked')) $o.parent().addClass(c.checkboxClass+'-on');
			}else if($o.attr('type')=='radio'){
				$o.css({opacity:0}).wrap($w);
				$o.parent().append('<em>&#10004;</em>')
				$o.on('change', function(e){
					$('input[name="' + $o.prop('name') + '"]').each(function(){
						$(this).parent().removeClass(c.radioClass+'-on');
					});
					if($o.is(':checked')) $o.parent().addClass(c.radioClass+'-on');
				});
				if($o.is(':checked')) $o.parent().addClass(c.radioClass+'-on');
			}
		});
	};
	//
	$.fn.actionTable = function(params){
		var conf = $.extend({
			tableElement:'table',
			checkboxInTable:'td.el-chk input[type="checkbox"]',
			checkboxAll:'.un-ls-action input[type="checkbox"]',
			sortFunction:undefined
		}, params);
		return this.each(function(){
			var $o=$(this), c=conf, f=this, $table=$(c.tableElement, $o), $chb_table=$(c.checkboxInTable, $table), $chb_all=$(c.checkboxAll, $o), state, $fx_head=$('<div class="bl-ls-fixed bl-ls"></div>'), sort_function;
			if(!$table.length) return false;
			sort_function={
        'int':function(a,b){return parseInt(a, 10) - parseInt(b,10)},
        'float':function(a,b){return parseFloat(a) - parseFloat(b)},
        'string':function(a,b){if(a<b) return -1; if(a>b) return +1; return 0},
				'l-word':function(a,b){
					var a_r=a.split(" "), b_r=b.split(" ");
					if(a_r[a_r.length-1].toUpperCase()<b_r[b_r.length-1].toUpperCase()) return -1; if(a_r[a_r.length-1].toUpperCase()>b_r[b_r.length-1].toUpperCase()) return +1; return 0
				},
				'date':function(a,b){aDate=f._date_from_string(a); bDate=f._date_from_string(b); return aDate-bDate},
				'reverse-string':function(a,b){if(b<a) return -1; if(b>a) return +1; return 0}
      };
			$.extend(f,{
				_arrays_equal:function(a,b){return !!a && !!b && !(a<b || b<a)},
				_date_from_string:function(str){
					var pattern=str.match(/^(\d{1,2})-(\d{1,2})-(\d{4})$/);
					return (pattern) ? new Date(pattern[3], pattern[2]-1, pattern[1]) : null;
				},
				_move:function(){
					$fx_head.append($('<table></table>').append($table.find('thead').clone()));
					$('body').append($fx_head.width($table.width()));
					f._scroll_check();
					$fx_head.find('th').each(function(i){
						$(this).on('click', function(){
							$table.find('thead th').eq(i).trigger('click');
						})
					})
					$(window).on('scroll resize',function() {
						f._scroll_check();
					});
				},
				_scroll_check:function(){
  				var scr_top=$(window).scrollTop(), tbl_top=$table.offset().top, tbl_btm=$table.height()+tbl_top-$fx_head.height();
  				if(tbl_top<scr_top && tbl_btm>scr_top){
						if(_ie7){
							$fx_head.css({position:'absolute', top:scr_top, left:$table.offset().left});
						}else{
							$fx_head.css({position:'fixed', top:0, left:$table.offset().left-$(window).scrollLeft()});
						}
  					$fx_head.show();
  				}else if(tbl_top>scr_top){
						$fx_head.hide();
					}else{
  					$fx_head.css({position:'absolute', top:tbl_btm, left:$table.offset().left});
  					$fx_head.show();
  				}
				},
				_chb_tbl_emulation:function(){
					$chb_table.each(function(){
						var $chb=$(this);
						$chb.css({opacity:0}).wrap('<span class="el-btn-chk"></span>');
						$chb.on('change', function(){
							if($chb.is(':checked')){
								$chb.parent().addClass('el-btn-chk-on');
								$chb.parents('tr').addClass('el-selected');
							}else{
								$chb.parent().removeClass('el-btn-chk-on');
								$chb.parents('tr').removeClass('el-selected');
							}
						})
					});
				},
				_chb_all_emulation:function(){
					$chb_all.each(function(){
						var $chb=$(this);
						$chb.css({opacity:0}).wrap('<span class="el-btn-chk"></span>');
						$chb.on('change', function(){
							if(state==undefined){state=$chb.prop('checked')}
							if(state){
								$chb.parent().addClass('el-btn-chk-on').removeClass('el-btn-chk-few');
								//$table.addClass('un-tbl-chk')
							}else{
								$chb.parent().removeClass('el-btn-chk-on');
								//$table.removeClass('un-tbl-chk')
								if($chb_table.filter(":checked").length){
									$chb.parent().addClass('el-btn-chk-few');
									//$table.addClass('un-tbl-chk')
								}else{
									$chb.parent().removeClass('el-btn-chk-few');
								}
							}
						})
					});
				},
				_checkbox_action:function(){
					f._chb_tbl_emulation(); f._chb_all_emulation();
					$chb_all.on('click', function(e){
						state=$(e.currentTarget).prop('checked');
						$chb_all.prop('checked', state).change();
						$chb_table.prop('checked', state).change();
					}).change();
					$chb_table.on('click', function(e){
						state=$chb_table.filter(":not(:checked)").length === 0;
						$chb_all.prop('checked', state).change();
					}).change()
					
				},
				_sort_map:function(arr, sorting, reverse_column){
					var map=[], index=0;
					if(reverse_column){
						for(var i=arr.length-1; i >= 0; i--){map.push(i)}
					}else{
						var sorted=arr.slice(0).sort(sorting);
						for(var i=0; i<arr.length; i++){
							index=$.inArray(arr[i], sorted);
							while($.inArray(index, map) != -1){index++}
							map.push(index);
						}
					}
					return map;
				},
				_apply_sort_map:function(arr, map){
					var clone=arr.slice(0), newIndex=0;
					for(var i=0; i<map.length; i++){
						newIndex = map[i];
						clone[newIndex] = arr[i];
					}
					return clone;
				},
				_apply_sort_th:function(obj, in_this, in_sort){
					obj.find('th').data('sort-dir', null).removeClass('el-sort-desc el-sort-asc').find('.el-arrow').remove();
          in_this.data('sort-dir', in_sort).addClass('el-sort-'+in_sort).append('<span class="el-arrow"></span>');
				}
			});
			$table.find('th[title]').each(function(){
				$(this).aTooltip({tipClass:'bl-tbl-tip', ifClick:false, xOffset:20, yOffset:5, tipPosition:'top'});
			});
			f._checkbox_action();
			f._move();
			$table.on('click', 'th', function(){
        var trs=$table.children('tbody').children('tr'), $this=$(this), th_index=0, dir={ASC:'asc', DESC:'desc'};
        $table.find('th').slice(0, $this.index()).each(function(){
          var cols=$(this).attr('colspan') || 1;
          th_index+=parseInt(cols,10);
        });
        var sort_dir=$this.data('sort-dir') === dir.ASC ? dir.DESC : dir.ASC;
        if(sort_dir==dir.DESC)
          var type=$this.data('sort-desc') || $this.data('sort') || null;
        else
          var type=$this.data('sort') || null;
        if(type===null) return;
        $table.trigger('beforetablesort', {column:th_index, direction:sort_dir});
        $table.css('display');
        setTimeout(function(){
          var column=[], sortMethod=sort_function[type];
          trs.each(function(index,tr){
            var $e = $(tr).children().eq(th_index);
            var sort_val=$e.data('sort-value'), order_by=typeof(sort_val) !== 'undefined' ? sort_val : $e.text();
            column.push(order_by);
          });
          var reverse_column=!!$this.data('sort-dir') && !$this.data('sort-desc'), theMap=f._sort_map(column, sortMethod, reverse_column);
          f._apply_sort_th($table, $table.find('th').eq(th_index), sort_dir);
					f._apply_sort_th($fx_head, $fx_head.find('th').eq(th_index), sort_dir);
          var sortedTRs = $(f._apply_sort_map(trs, theMap));
          $table.children('tbody').append(sortedTRs);
          $table.trigger('aftertablesort', {column:th_index, direction:sort_dir});
          $table.css('display');
        }, 10);
      });
		});
	};
	//
})(jQuery);
var _ie7=false; if(document.all && !document.querySelector){_ie7=true}
/* json2.js
 * 2008-01-17
 * Public Domain
 * No warranty expressed or implied. Use at your own risk.
 * See http://www.JSON.org/js.html
*/
if(!this.JSON){JSON=function(){function f(n){return n<10?'0'+n:n;}
Date.prototype.toJSON=function(){return this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z';};var m={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};function stringify(value,whitelist){var a,i,k,l,r=/["\\\x00-\x1f\x7f-\x9f]/g,v;switch(typeof value){case'string':return r.test(value)?'"'+value.replace(r,function(a){var c=m[a];if(c){return c;}
c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+
(c%16).toString(16);})+'"':'"'+value+'"';case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
if(typeof value.toJSON==='function'){return stringify(value.toJSON());}
a=[];if(typeof value.length==='number'&&!(value.propertyIsEnumerable('length'))){l=value.length;for(i=0;i<l;i+=1){a.push(stringify(value[i],whitelist)||'null');}
return'['+a.join(',')+']';}
if(whitelist){l=whitelist.length;for(i=0;i<l;i+=1){k=whitelist[i];if(typeof k==='string'){v=stringify(value[k],whitelist);if(v){a.push(stringify(k)+':'+v);}}}}else{for(k in value){if(typeof k==='string'){v=stringify(value[k],whitelist);if(v){a.push(stringify(k)+':'+v);}}}}
return'{'+a.join(',')+'}';}}
return{stringify:stringify,parse:function(text,filter){var j;function walk(k,v){var i,n;if(v&&typeof v==='object'){for(i in v){if(Object.prototype.hasOwnProperty.apply(v,[i])){n=walk(i,v[i]);if(n!==undefined){v[i]=n;}}}}
return filter(k,v);}
if(/^[\],:{}\s]*$/.test(text.replace(/\\./g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof filter==='function'?walk('',j):j;}
throw new SyntaxError('parseJSON');}};}();}
/*
	Masked Input plugin for jQuery
	Copyright (c) 2007-2013 Josh Bush (digitalbush.com)
	Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license)
	Version: 1.3.1
*/
(function(e){function t(){var e=document.createElement("input"),t="onpaste";return e.setAttribute(t,""),"function"==typeof e[t]?"paste":"input"}var n,a=t()+".mask",r=navigator.userAgent,i=/iphone/i.test(r),o=/android/i.test(r);e.mask={definitions:{9:"[0-9]",a:"[A-Za-z]","*":"[A-Za-z0-9]"},dataName:"rawMaskFn",placeholder:"_"},e.fn.extend({caret:function(e,t){var n;if(0!==this.length&&!this.is(":hidden"))return"number"==typeof e?(t="number"==typeof t?t:e,this.each(function(){this.setSelectionRange?this.setSelectionRange(e,t):this.createTextRange&&(n=this.createTextRange(),n.collapse(!0),n.moveEnd("character",t),n.moveStart("character",e),n.select())})):(this[0].setSelectionRange?(e=this[0].selectionStart,t=this[0].selectionEnd):document.selection&&document.selection.createRange&&(n=document.selection.createRange(),e=0-n.duplicate().moveStart("character",-1e5),t=e+n.text.length),{begin:e,end:t})},unmask:function(){return this.trigger("unmask")},mask:function(t,r){var c,l,s,u,f,h;return!t&&this.length>0?(c=e(this[0]),c.data(e.mask.dataName)()):(r=e.extend({placeholder:e.mask.placeholder,completed:null},r),l=e.mask.definitions,s=[],u=h=t.length,f=null,e.each(t.split(""),function(e,t){"?"==t?(h--,u=e):l[t]?(s.push(RegExp(l[t])),null===f&&(f=s.length-1)):s.push(null)}),this.trigger("unmask").each(function(){function c(e){for(;h>++e&&!s[e];);return e}function d(e){for(;--e>=0&&!s[e];);return e}function m(e,t){var n,a;if(!(0>e)){for(n=e,a=c(t);h>n;n++)if(s[n]){if(!(h>a&&s[n].test(R[a])))break;R[n]=R[a],R[a]=r.placeholder,a=c(a)}b(),x.caret(Math.max(f,e))}}function p(e){var t,n,a,i;for(t=e,n=r.placeholder;h>t;t++)if(s[t]){if(a=c(t),i=R[t],R[t]=n,!(h>a&&s[a].test(i)))break;n=i}}function g(e){var t,n,a,r=e.which;8===r||46===r||i&&127===r?(t=x.caret(),n=t.begin,a=t.end,0===a-n&&(n=46!==r?d(n):a=c(n-1),a=46===r?c(a):a),k(n,a),m(n,a-1),e.preventDefault()):27==r&&(x.val(S),x.caret(0,y()),e.preventDefault())}function v(t){var n,a,i,l=t.which,u=x.caret();t.ctrlKey||t.altKey||t.metaKey||32>l||l&&(0!==u.end-u.begin&&(k(u.begin,u.end),m(u.begin,u.end-1)),n=c(u.begin-1),h>n&&(a=String.fromCharCode(l),s[n].test(a)&&(p(n),R[n]=a,b(),i=c(n),o?setTimeout(e.proxy(e.fn.caret,x,i),0):x.caret(i),r.completed&&i>=h&&r.completed.call(x))),t.preventDefault())}function k(e,t){var n;for(n=e;t>n&&h>n;n++)s[n]&&(R[n]=r.placeholder)}function b(){x.val(R.join(""))}function y(e){var t,n,a=x.val(),i=-1;for(t=0,pos=0;h>t;t++)if(s[t]){for(R[t]=r.placeholder;pos++<a.length;)if(n=a.charAt(pos-1),s[t].test(n)){R[t]=n,i=t;break}if(pos>a.length)break}else R[t]===a.charAt(pos)&&t!==u&&(pos++,i=t);return e?b():u>i+1?(x.val(""),k(0,h)):(b(),x.val(x.val().substring(0,i+1))),u?t:f}var x=e(this),R=e.map(t.split(""),function(e){return"?"!=e?l[e]?r.placeholder:e:void 0}),S=x.val();x.data(e.mask.dataName,function(){return e.map(R,function(e,t){return s[t]&&e!=r.placeholder?e:null}).join("")}),x.attr("readonly")||x.one("unmask",function(){x.unbind(".mask").removeData(e.mask.dataName)}).bind("focus.mask",function(){clearTimeout(n);var e;S=x.val(),e=y(),n=setTimeout(function(){b(),e==t.length?x.caret(0,e):x.caret(e)},10)}).bind("blur.mask",function(){y(),x.val()!=S&&x.change()}).bind("keydown.mask",g).bind("keypress.mask",v).bind(a,function(){setTimeout(function(){var e=y(!0);x.caret(e),r.completed&&e==x.val().length&&r.completed.call(x)},0)}),y()}))}})})(jQuery);
